<!--
 * @Description: 门店管理表单弹窗
-->
<template>
  <a-drawer :title="formTitle" :open="visible" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 8 }">
      <a-card title="基本信息" class="smart-margin-bottom10">
        <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
          <a-col :span="21">
            <a-row :gutter="{ sm: 8, md: 16, lg: 24 }">
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="门店名称" name="store_name">
                  <a-input v-model:value="form.store_name" placeholder="请输入门店名称" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="简称" name="store_short_name">
                  <a-input v-model:value="form.store_short_name" placeholder="请输入简称" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="联系人" name="contacts">
                  <a-input v-model:value="form.contacts" placeholder="请输入联系人" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="联系电话" name="phone">
                  <a-input v-model:value="form.phone" placeholder="请输入联系电话" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="唯一电话" name="only_phone">
                  <a-input v-model:value="form.only_phone" placeholder="请输入唯一识别号" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="密码" name="password">
                  <a-input v-model:value="form.password" placeholder="请输入密码" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="地址" name="address">
                  <a-input v-model:value="form.address" placeholder="请输入地址" readonly>
                    <template #addonAfter>
                      <a-tooltip title="选择地址" @click="handleIconClick">
                        <EnvironmentOutlined style="color: rgba(0, 0, 0, 0.45)" />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="结算类型" name="payment_type">
                  <a-select ref="select" v-model:value="form.payment_type" placeholder="结算类型">
                    <a-select-option :value="1">现结</a-select-option>
                    <a-select-option :value="2">欠款</a-select-option>
                    <a-select-option :value="3">预付款</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="所属片区" name="store_region_id">
                  <a-select v-model:value="form.store_region_id" :options="optionsRegion" placeholder="所属片区" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="门店类型" name="store_level_id">
                  <a-select v-model:value="form.store_level_id" :options="optionsLevel" placeholder="门店类型" allowClear />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="渠道" name="channel">
                  <a-input v-model:value="form.channel" placeholder="请输入渠道" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="排序" name="sort">
                  <a-input v-model:value="form.sort" placeholder="请输入排序" />
                </a-form-item>
              </a-col>
              <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
                <a-form-item label="备注" name="remark">
                  <a-input v-model:value="form.remark" placeholder="请输入备注" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="3">
            <a-col :xs="24" :lg="12" :xl="8" :xxl="6">
              <a-form-item label="" name="store_img">
                <FileUpload v-model:value="form.store_img" :default-file-list="form.store_img" buttonText="上传logo" :maxUploadSize="1" :maxSize="1" accept=".jpeg,.jpg,.png" />
              </a-form-item>
            </a-col>
          </a-col>
        </a-row>
      </a-card>
    </a-form>
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
  <!-- 地图组件 -->
  <Map :isShow="showForm" :defaultAddress="defaultAddress" :defaultPoint="defaultPoint" @getPosition="getPosition" />
</template>
<script setup lang="ts">
import Map from './shop-map-modal.vue'
import { ref, unref, computed, nextTick, onMounted } from 'vue'
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import FileUpload from '@/components/support/file-upload/index.vue'
import { storeApi } from '@/api/business/data/store-api'
import { searchApi } from '@/api/search/search-api'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reload-list'])

// 组件ref
const formRef = ref()

const formDefault = {
  store_no: '',
  // 门店名称
  store_name: '',
  // 简称
  store_short_name: '',
  // 联系人
  contacts: '',
  // 联系电话
  phone: '',
  // 唯一识别号
  only_phone: '',
  // 密码
  password: '',
  // 地址
  address: '',
  // 经度
  lon: '',
  // 纬度
  lat: '',
  // 支付类型
  payment_type: undefined,
  // 所属片区
  store_region_id: null,
  // 门店类型
  store_level_id: undefined,
  // 渠道
  channel: '',
  // 排序
  sort: '',
  // 备注
  remark: '',
  // store_img
  store_img: ''
}

const form = ref({ ...formDefault })
const rules = {
  store_name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  contacts: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: ['change', 'blur'] }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  only_phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  lon: [{ required: true, message: '请输入经度', trigger: 'blur' }],
  lat: [{ required: true, message: '请输入纬度', trigger: 'blur' }]
}

onMounted(() => {
  searchSalesman()
  searchRegion()
  searchLevel()
})

// ---------------------------- 下拉框 ----------------------------
// 业务员
const optionsSalesman = ref([])

const searchSalesman = async () => {
  const res = await searchApi.salesmanList({ fields: 'id,rename' })
  optionsSalesman.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.rename
    }
  })
}

// 所属片区
const optionsRegion = ref([])

const searchRegion = async () => {
  const res = await searchApi.regionList({ fields: 'id,name' })
  optionsRegion.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.name
    }
  })
}

// 门店类型
const optionsLevel = ref([])

const searchLevel = async () => {
  const res = await searchApi.levelList({ fields: 'id,level_name' })
  optionsLevel.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.level_name
    }
  })
}

// 是否展示抽屉
const visible = ref(false)

function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (rowData && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
    form.value.password = ''
  }
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = _.cloneDeep(formDefault)
  visible.value = false
}

function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        const formRef = unref(form)
        if (Array.isArray(formRef.dealer_id)) {
          formRef.dealer_id = formRef.dealer_id.join(',')
        }
        if (formRef.id) {
          await storeApi.editStore(formRef)
        } else {
          await storeApi.addStore(formRef)
        }
        message.success('操作成功')
        onClose()
        emit('reload-list')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}
// ---------------------------- 地图选点 ----------------------------
const showForm = ref(false)
const defaultAddress = ref('')
const defaultPoint = ref([])
const handleIconClick = () => {
  if (form.value != undefined) {
    defaultAddress.value = form.value.address
    defaultPoint.value = [form.value.lon, form.value.lat]
  }
  showForm.value = true
}
const getPosition = (infoObj) => {
  showForm.value = false
  if (infoObj.address) {
    form.value.address = infoObj.address
    form.value.lon = infoObj.point[0]
    form.value.lat = infoObj.point[1]
  }
  formRef.value.clearValidate(['address'])
}

defineExpose({
  showDrawer
})

// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新增'))
</script>
